var validator = require('validator');
var _ = require('lodash');
var u = require('util');
var at = require('../common/at');
var message = require('../common/message');

var EventProxy = require('eventproxy');

var User = require('../proxy').User;
var Topic = require('../proxy').Topic;
var Reply = require('../proxy').Reply;
var config = require('../config');
var JPush = require('jpush-sdk');
var jPushClient = JPush.buildClient(config.jpush.appKey, config.jpush.appMasterKey);

/**
 * 委派任务 从 add 方法复制 而来
 */
exports.assign = function(req, res, next) {
    var content = req.body.r_content;
    var topic_id = req.params.topic_id;
    var reply_id = req.body.reply_id;

    var str = validator.trim(content);
    if (str === '') {
        res.status(422);
        // TODO
        // this should be validate in front page
        res.render('notify/notify', {
            error: '指派人不能为空！'
        });
        return;
    }

    var ep = EventProxy.create();
    ep.fail(next);

    Topic.getTopic(topic_id, ep.doneLater(function(topic) {
        if (!topic) {
            ep.unbind();
            // just 404 page
            return next();
        }
        ep.emit('topic', topic);
    }));

    ep.all('topic', function(topic) {
        User.getUserById(topic.author_id, ep.done('topic_author'));
    });

    ep.all('topic', 'topic_author', function(topic, topicAuthor) {
        var assignee = at.fetchUsers(content)[0];
        
        var eam_wo_status = topic.eam_wo_status;
        var tab = null;
        switch (topic.eam_wo_category) {
            case 'inspection':
                eam_wo_status = 1;
                topic.eam_inspection_assignee = assignee;
                tab = '检查工单';
                break;
            case 'maintenance':
                eam_wo_status = 4;
                topic.eam_maintain_assignee = assignee;
                tab = '维修工单';
                break;
            default:
                tab = '工单';
                break;
        }
        topic.eam_wo_status = eam_wo_status;
        topic.save(function(err) {
            Reply.newAndSave(u.format("[工作流] %s 将任务委派给 %s", topicAuthor.loginname, assignee), topic_id, req.session.user._id, reply_id, ep.done(function(reply) {
                jPushClient.push()
                    .setPlatform('ios', 'android')
                    .setAudience(JPush.alias(assignee))
                    .setNotification(JPush.ios(u.format("[工作流] %s 将任务 %s %s 委派给您。", topicAuthor.loginname, tab, topic.eam_wo_id), 'happy'))
                    .setMessage('eam msg', 'eam wo', topic.eam_wo_category, {
                        'eam_wo_id': topic.eam_wo_id,
                        '_id': topic._id
                    })
                    // get api https://github.com/jpush/jpush-api-nodejs-client/blob/master/lib/JPush/PushPayload.js
                    .setOptions(null, null, null, config.jpush.isProduction)
                    .send(function(err, res) {
                        if (err) {
                            console.log(err.message);
                        } else {
                            console.log('Sendno: ' + res.sendno);
                            console.log('Msg_id: ' + res.msg_id);
                        }
                    });

                Topic.updateLastReply(topic_id, reply._id, ep.done(function() {
                    ep.emit('reply_saved', reply);
                    //发送at消息，并防止重复 at 作者
                    var newContent = content.replace('@' + topicAuthor.loginname + ' ', '');
                    at.sendMessageToMentionUsers(newContent, topic_id, req.session.user._id, reply._id);
                }));
            }));

            User.getUserById(req.session.user._id, ep.done(function(user) {
                user.score += 5;
                user.reply_count += 1;
                user.save();
                req.session.user = user;
                ep.emit('score_saved');
            }));
        });
    });

    ep.all('reply_saved', 'topic', function(reply, topic) {
        if (topic.author_id.toString() !== req.session.user._id.toString()) {
            message.sendReplyMessage(topic.author_id, req.session.user._id, topic._id, reply._id);
        }
        ep.emit('message_saved');
    });

    ep.all('reply_saved', 'message_saved', 'score_saved', function(reply) {
        res.redirect('/eam/' + topic_id + '#' + reply._id);
    });
};

/**
 * 添加回复
 */
exports.add = function(req, res, next) {
    var content = req.body.r_content;
    var topic_id = req.params.topic_id;
    var reply_id = req.body.reply_id;

    var str = validator.trim(content);
    if (str === '') {
        res.status(422);
        res.render('notify/notify', {
            error: '回复内容不能为空！'
        });
        return;
    }

    var ep = EventProxy.create();
    ep.fail(next);

    Topic.getTopic(topic_id, ep.doneLater(function(topic) {
        if (!topic) {
            ep.unbind();
            // just 404 page
            return next();
        }
        ep.emit('topic', topic);
    }));

    ep.all('topic', function(topic) {
        User.getUserById(topic.author_id, ep.done('topic_author'));
    });

    ep.all('topic', 'topic_author', function(topic, topicAuthor) {
        Reply.newAndSave(content, topic_id, req.session.user._id, reply_id, ep.done(function(reply) {
            Topic.updateLastReply(topic_id, reply._id, ep.done(function() {
                ep.emit('reply_saved', reply);
                //发送at消息，并防止重复 at 作者
                var newContent = content.replace('@' + topicAuthor.loginname + ' ', '');
                at.sendMessageToMentionUsers(newContent, topic_id, req.session.user._id, reply._id);
            }));
        }));

        User.getUserById(req.session.user._id, ep.done(function(user) {
            user.score += 5;
            user.reply_count += 1;
            user.save();
            req.session.user = user;
            ep.emit('score_saved');
        }));
    });

    ep.all('reply_saved', 'topic', function(reply, topic) {
        if (topic.author_id.toString() !== req.session.user._id.toString()) {
            message.sendReplyMessage(topic.author_id, req.session.user._id, topic._id, reply._id);
        }
        ep.emit('message_saved');
    });

    ep.all('reply_saved', 'message_saved', 'score_saved', function(reply) {
        res.redirect('/eam/' + topic_id + '#' + reply._id);
    });
};

/**
 * 删除回复信息
 */
exports.delete = function(req, res, next) {
    var reply_id = req.body.reply_id;
    Reply.getReplyById(reply_id, function(err, reply) {
        if (err) {
            return next(err);
        }

        if (!reply) {
            res.status(422);
            res.json({
                status: 'no reply ' + reply_id + ' exists'
            });
            return;
        }
        if (reply.author_id.toString() === req.session.user._id.toString()) {
            reply.remove();
            res.json({
                status: 'success'
            });

            if (!reply.reply_id) {
                reply.author.score -= 5;
                reply.author.reply_count -= 1;
                reply.author.save();
            }
        } else {
            res.json({
                status: 'failed'
            });
            return;
        }

        Topic.reduceCount(reply.topic_id, _.noop);
    });
};
/*
 打开回复编辑器
 */
exports.showEdit = function(req, res, next) {
    var reply_id = req.params.reply_id;

    Reply.getReplyById(reply_id, function(err, reply) {
        if (!reply) {
            res.status(422);
            res.render('notify/notify', {
                error: '此回复不存在或已被删除。'
            });
            return;
        }
        if (req.session.user._id.equals(reply.author_id) || req.session.user.is_admin) {
            res.render('reply/edit', {
                reply_id: reply._id,
                content: reply.content
            });
        } else {
            res.status(403);
            res.render('notify/notify', {
                error: '对不起，你不能编辑此回复。'
            });
        }
    });
};
/*
 提交编辑回复
 */
exports.update = function(req, res, next) {
    var reply_id = req.params.reply_id;
    var content = req.body.t_content;

    Reply.getReplyById(reply_id, function(err, reply) {
        if (!reply) {
            res.render('notify/notify', {
                error: '此回复不存在或已被删除。'
            });
            return;
        }

        if (String(reply.author_id) === req.session.user._id.toString() || req.session.user.is_admin) {

            if (content.trim().length > 0) {
                reply.content = content;
                reply.save(function(err) {
                    if (err) {
                        return next(err);
                    }
                    res.redirect('/topic/' + reply.topic_id + '#' + reply._id);
                });
            } else {
                res.render('notify/notify', {
                    error: '回复的字数太少。'
                });
            }
        } else {
            res.render('notify/notify', {
                error: '对不起，你不能编辑此回复。'
            });
        }
    });
};

exports.up = function(req, res, next) {
    var replyId = req.params.reply_id;
    var userId = req.session.user._id;
    Reply.getReplyById(replyId, function(err, reply) {
        if (err) {
            return next(err);
        }
        if (reply.author_id.equals(userId) && !config.debug) {
            // 不能帮自己点赞
            res.send({
                success: false,
                message: '呵呵，不能帮自己点赞。',
            });
        } else {
            var action;
            reply.ups = reply.ups || [];
            var upIndex = reply.ups.indexOf(userId);
            if (upIndex === -1) {
                reply.ups.push(userId);
                action = 'up';
            } else {
                reply.ups.splice(upIndex, 1);
                action = 'down';
            }
            reply.save(function() {
                res.send({
                    success: true,
                    action: action
                });
            });
        }
    });
};
